package com.zjz.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.zjz.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
public class UserController {
    @RequestMapping("/j1")
    @ResponseBody  // 只要加了ResponseBody 就不会走视图解析器，会直接返回一个字符串
    public String json1() throws JsonProcessingException {

        User user = new User("zjz", 3, "nan");

        ObjectMapper mapper = new ObjectMapper();

        String s = mapper.writeValueAsString(user);
        return s;
    }



    @RequestMapping("/j2")
    @ResponseBody
    public String json2() throws JsonProcessingException {


        List<User> list = new ArrayList<>();
        list.add(new User("zjz0",12,"z"));
        list.add(new User("zjz1",22,"z"));
        list.add(new User("zjz2",32,"z"));
        list.add(new User("zjz3",42,"z"));
        list.add(new User("zjz4",52,"z"));
        list.add(new User("zjz5",62,"z"));
        list.add(new User("zjz6",72,"z"));
        list.add(new User("zjz7",82,"z"));
        list.add(new User("zjz8",92,"z"));
        list.add(new User("zjz9",102,"z"));

        ObjectMapper mapper = new ObjectMapper();
        String s = mapper.writeValueAsString(list);


        return s;
    }

    @RequestMapping("/j3")
    @ResponseBody
    public String json3() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String format = simpleDateFormat.format(new Date());

        // 直接返回是一个时间戳
        String s1 = mapper.writeValueAsString(format);
        ObjectMapper configure = mapper.configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false);
        mapper.setDateFormat(simpleDateFormat);
        String s = mapper.writeValueAsString((new Date()));

        return s;
    }
}
